# -*- coding: utf-8 -*-

"""
This script prepares the environment, installs dependencies if necessary, and performs a series of steps to generate files and documents for a homework tool.

Steps:
1. Generate dot files from input files.
2. Adapt dot files for Chinese characters.
3. Generate SVG files from dot files.
4. Generate PNG files from dot files.
5. Generate highlighted code snapshots from source files.
6. Generate a document with the generated files and basic information.

Note: The script assumes the presence of certain dependencies and directories.
"""

# Rest of the code...
print("正在准备环境........")
try:
    import os
    import sys
    import subprocess
    from pygments import highlight
    from pygments.lexers import PythonLexer
    from pygments.formatters import ImageFormatter
    import matplotlib.pyplot as plt
    from docx.shared import Inches

    from docx import Document
except:
    print("正在安装依赖........")
    os.system("pip install pygments")
    os.system("pip install matplotlib")
    os.system("pip install python-docx")
    os.system("pip install os")
    os.system("pip install sys")
    os.system("pip install subprocess")
    os.execl(sys.executable, sys.executable, *sys.argv)

print("正在准备环境........完成")

print("正在加载基本配置........")
yourName = "张三"
yourID = "123456789"
yourClass = "计算机科学与技术"
stepCount = 6
document_path = "input.docx"
plt.rcParams['font.family'] = 'Times New Roman'
plt.style.use('ggplot')
input_dir = "input"
file_list = []
for root, dirs, files in os.walk(input_dir):
    for file in files:
        file_list.append(file)
file_list.remove(document_path)
fileNum = len(file_list)
print("正在加载基本配置........完成")
print("正在清空临时文件夹........")
os.system("rm -rf ./temp")
print("正在清空临时文件夹........完成")
print("正在清空输出文件夹........")
os.system("rm -rf ./output")
print("正在清空输出文件夹........完成")
print("正在准备转换以下文件:{}".format(file_list))
print("正在准备生成文件夹........")
os.makedirs("./temp", exist_ok=True)
os.makedirs("./output/svg", exist_ok=True)
os.makedirs("./output/png", exist_ok=True)
os.makedirs("./output/codesnap", exist_ok=True)
print("正在准备生成文件夹........完成")

print("正在执行步骤(1/{}):生成dot........".format(stepCount))
for file in file_list:
    fileCount = file_list.index(file) + 1
    output_file = "./temp/" + file + ".dot"
    print("[{}/{}]在生成文件:{}".format(fileCount,fileNum,output_file))
    command = "\"bin/cxx2flow\" " + "input/"+file + " -o " + output_file
    print("[{}/{}]执行命令:{}".format(fileCount,fileNum,command))
    subprocess.run(command, shell=True)


print("正在执行步骤(2/{}):进行中文适配........".format(stepCount))

for file in file_list:
    fileCount = file_list.index(file) + 1
    dot_file = "./temp/" + file + ".dot"
    print("[{}/{}]在覆写文件:{}".format(fileCount,fileNum,dot_file))
    with open(dot_file, 'r',encoding='utf-8') as f:
        lines = f.readlines()
    lines.insert(1, 'node[fontname = "Fangsong"];\n')  # insert at second line
    with open(dot_file, 'w',encoding='utf-8') as f:
        f.writelines(lines)
print("正在执行步骤(3/{}):生成svg........".format(stepCount))

for file in file_list:
    fileCount = file_list.index(file) + 1
    input_file = "temp/" + file + ".dot"
    output_file = "./output/svg/" + file + ".svg"
    print("[{}/{}]在生成文件:{}".format(fileCount,fileNum,output_file))
    command = "\"Graphviz/bin/dot\" " +"-Tsvg "+ input_file + " -o " + output_file
    print("[{}/{}]执行命令:{}".format(fileCount,fileNum,command))
    subprocess.run(command, shell=True)
    
print("正在执行步骤(4/{}):生成png........".format(stepCount))

for file in file_list:
    fileCount = file_list.index(file) + 1
    input_file = "./temp/" + file + ".dot"
    output_file = "./output/png/" + file + ".png"
    print("[{}/{}]在生成文件:{}".format(fileCount,fileNum,output_file))
    command = "\"Graphviz/bin/dot\" -Tpng " + input_file + " -o " + output_file
    print("[{}/{}]执行命令:{}".format(fileCount,fileNum,command))
    subprocess.run(command, shell=True)
    

print("正在执行步骤(5/{}):生成图片........".format(stepCount))


for file in file_list:
    fileCount = file_list.index(file) + 1
    source_file = "./input/" + file 
    output_file = "./output/codesnap/" + file + ".png"
    print("[{}/{}]在生成文件:{}".format(fileCount,fileNum,output_file))

    with open(source_file, 'r',encoding='utf-8') as f:
        code = f.read()

    formatter = ImageFormatter(font_name='Times New Roman', style='default')
    highlighted_code = highlight(code, PythonLexer(), formatter)

    with open(output_file, 'wb') as f:
        f.write(highlighted_code)
        
print("正在执行步骤(6/{}):生成文档........".format(stepCount))
print("正在打开文档:{}".format(document_path))
document = Document("input/"+document_path)
print("正在写入文档:{}".format(document_path))
# Access the content of the document
for paragraph in document.paragraphs:
    for run in paragraph.runs:
        print(run.text)
        if "实验步骤" in run.text:
            if "源程序" in run.text:
                continue
            print("正在写入实验步骤......")
            for file in file_list:
                fileCount = file_list.index(file) + 1
                print("[{}/{}]正在写入实验步骤:{}".format(fileCount,fileNum,file))
                paragraph.add_run().add_picture('output/png/'+file+'.png', width=Inches(6.25))
        if "源代码" in run.text:
            print("正在写入源代码......")
            for file in file_list:
                fileCount = file_list.index(file) + 1
                print("[{}/{}]正在写入源代码:{}".format(fileCount,fileNum,file))
                paragraph.add_run().add_picture('output/codesnap/'+file+'.png', width=Inches(6.25))
print("正在写入基本信息......")
document.save('output/'+yourName+yourID+'.docx')
print("***********************************")
print("*                工作完成！       * ")
print("***********************************")